package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFRegionUtil;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    public String list(Model model, EmployeeQueryObject qo) {
        PageInfo<Employee> pageInfo = employeeService.query(qo);
        List<Department> departments = departmentService.listAll();
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("qo", qo);
        model.addAttribute("depts", departments);
        return "employee/list";
    }

    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            employeeService.delete(id);
        }
        return "redirect:/employee/list.do";
    }

    @RequestMapping("/input")
    public String input(Long id, Model model) {
        //查询所有角色
        List<Role> roles = roleService.listAll();
        if (id != null) {
            Employee employee = employeeService.get(id);
            model.addAttribute("employee", employee);
        }
        List<Department> departments = departmentService.listAll();
        model.addAttribute("depts", departments);
        model.addAttribute("roles", roles);
        return "employee/input";
    }

    @ResponseBody
    @RequestMapping("/saveOrUpdate")
    public JsonResult saveOrUpdate(Employee employee, Long[] ids) {
        try {
            if (employee.getId() == null) {
                employeeService.save(employee, ids);
            } else {
                employeeService.update(employee, ids);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false, "保存失败");
        }

    }

    @ResponseBody
    @RequestMapping("/updatePwd")
    public JsonResult updatePwd(String oldPassword, String newPassword, Long employeeId) {

        if (oldPassword == null) {
            return new JsonResult(false, "密码不能为空");
        }
        Employee employee = employeeService.get(employeeId);
        if (!employee.getPassword().equals(oldPassword)) {
            return new JsonResult(false, "密码错误，修改密码失败，请确认并输入正确的密码");
        }
        if (newPassword == null) {
            return new JsonResult(false, "密码不能为空");
        } else {
            employeeService.updatePassword(newPassword, employeeId);
            return new JsonResult();
        }
    }

    @RequestMapping("/skipUpdatePwd")
    public String skipUpdatePwd(Long id, Model model) {
        Employee employee = employeeService.get(id);
        model.addAttribute("employee", employee);
        return "/common/updatePwd";
    }

    @RequestMapping("/skipResetPassword")
    public String skipResetPassword(Model model, Long id) {
        Employee employee = employeeService.get(id);
        List<String> list = UserContext.getExpression();
        model.addAttribute("employee", employee);
        return "/common/resetPwd";
    }

    @ResponseBody
    @RequestMapping("/resetPwd")
    public JsonResult resetPwd(String newPassword, Long employeeId) {
        if (!UserContext.getCurrentUser().isAdmin()) {
            return new JsonResult(false, "只有管理员才能重置密码");
        }
        if (newPassword == null) {
            return new JsonResult(false, "密码不能为空");
        } else {
            employeeService.updatePassword(newPassword, employeeId);
            HttpSession session = UserContext.getSession();
            session.invalidate();
            return new JsonResult();
        }
    }

    @RequestMapping("/batchDelete")
    public JsonResult batchDelete(Long[] ids) {
        if (ids != null && ids.length > 0) {
            employeeService.batchDelete(ids);
            return new JsonResult();
        } else {
            return new JsonResult(false, "操作失败");
        }
    }

    @ResponseBody
    @RequestMapping("/checkName")
    public Map<String, Boolean> checkName(String name, Long id) {
        Map<String, Boolean> map = new HashMap();
        if (id != null) {
            Employee employee = employeeService.checkEmployeeById(id);
            if (employee.getName().contains(name)) {
                map.put("valid", true);
                return map;
            }
        }
        Employee employee = employeeService.checkEmployeeByName(name);
        if (employee!=null){
            if (employee.getName().contains(name)) {
                map.put("valid", false);
                return map;
            }
        }
        map.put("valid", true);
        return map;
    }

    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws IOException {
        //文件需要设置响应头，不然文件名会变成地址
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        //获取表格
        HSSFWorkbook workbook = employeeService.exportXls();

        //输出到浏览器
        workbook.write(response.getOutputStream());
    }
    @ResponseBody
    @RequestMapping("importXls")
    public JsonResult importXls(MultipartFile file) throws IOException {
        //读取上次的文件的输入流
        HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
        employeeService.importXls(workbook);
        return new JsonResult();
    }
    @ResponseBody
    @RequestMapping("/changeenablestate")
    public JsonResult changeenablestate(Long id) {
        if (id != null) {
            employeeService.changeEnableState(id);
            return new JsonResult();
        } else {
            return new JsonResult(false, "操作失败");
        }
    }
}


